/**
 * 初始化json变量
 */
function initJson () {
    var list = document.getElementsByTagName('json');
    var json = {};
    for (var i = 0; i < list.length; i++) {
        var item = list[i];
        json[item.getAttribute('name')] = JSON.parse(item.innerHTML);
    }
    return json;
}

layui.use(['element', 'jquery', 'layer', 'form', 'element', 'table'], function () {
    const $ = layui.jquery;
    const layer = layui.layer;
    const yumTitle = document.title;
    const form = layui.form;
    const element = layui.element;
    const table = layui.table;
    const tableObj = {};
    let json = initJson();
    let layerIndex;

    const dom = $('[data-jump="' + location.pathname + '"]');
    dom.parent().addClass('layui-this');

    $(document).on('click', '[ke-nav] a', function () {
        let url = $(this).data('jump');
        let title = $(this).data('title');
        if (url) {
            if (title) {
                document.title = yumTitle + ' - ' + title;
            } else {
                document.title = yumTitle;
            }
            $.pjax({
                url: url,
                container: '#ke-render'
            });
        }
    });
    // $(document).pjax('[ke-nav] a', '#ke-render', {
    //     url: 'data-jump'
    // });
    var initTable = function () {
        let els = $('[ke-table]');
        for (var i = 0; i < els.length; i++) {
            let item = els[i]
            let key = item.getAttribute('ke-table')
            let url = item.getAttribute('data-url')
            tableObj[key] = table.render({
                elem: els[i],
                cols: [json[key].columns.map((item) => {
                    if (item.width === 0) {
                        delete item.width
                    }
                    if (item.type === 'image') {
                        item.templet = function (d, c) {
                            // console.log(item);
                            return '<img src="' + d[item.field] + '" width="' + item.width + '"/>';
                        };
                    }
                    return item;
                })],
                url,
                headers: {
                    'x-response': 'table'
                },
                page: true,
                parseData (res) {
                    if (res.error) {
                        return {
                            'code': 1,
                            'msg': res.error
                        };
                    }
                    return {
                        'code': 0,
                        'count': res.count,
                        'data': res.list
                    }
                }
            });
        }
    };
    initTable();

    /// 注册加载层显隐事件
    $(document).on('pjax:send', function() {
        layerIndex = layer.load(1, {
            id: 'page',
        })
    });
    $(document).on('pjax:complete', function() {
        json = initJson();
        form.render();
        element.init();
        initTable();
        layer.close(layerIndex);
    });

    /// 表单处理
    form.on('submit(form)', function(data){
        let subidx = layer.load();

        $.ajax({
            type: data.form.method,
            data: data.field,
            datatype: 'json',
            headers: {
                'x-response': 'form'
            },
            success: function (result) {
                if (result.error) {
                    layer.msg(result.error);
                } else {
                    if (result.msg) {
                        layer.msg(result.msg)
                    }
                    if (result.url) {
                        setTimeout(() => {
                            $.pjax({
                                url: result.url,
                                container: '#ke-render'
                            })
                        }, 500)
                    }
                }
                // console.log('success', result)
            },
            error: function (result) {
                console.error('error', result);
                layer.msg('服务端错误');
            },
            complete: function () {
                layer.close(subidx);
            }
        });
        return false;
    });

    /// 搜索框
    form.on('submit(search)', function(data){
        let key = data.form.getAttribute('go');
        if (key && tableObj['table_' + key]) {
            tableObj['table_' + key].reload({
                where: data.field
            });
        }
        return false;
    });
});

